package net.bithappens.hnqe.impl.rest.provider;

import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;

import net.bithappens.hnqe.IllegalParamException;
import net.bithappens.hnqe.graph.EntryValue;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class EntryValueJsonAddapter implements JsonSerializer<Object>, JsonDeserializer<Object> {

	
	@Override
	public JsonElement serialize(Object object, Type type, JsonSerializationContext jsonSerializationContext) {

		return jsonSerializationContext.serialize(object, object.getClass());
		
	}
	
	
	@Override
	public Object deserialize(JsonElement jsonElement, Type type, 
		JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
	
		JsonObject jsonObj = jsonElement.getAsJsonObject();

		if(jsonObj.get("value").isJsonObject()){
			//in this case it must be a calendar
			JsonObject value = jsonObj.get("value").getAsJsonObject();
			long time = value.get("milliseconds").getAsLong();
			try {
				return new EntryValue(new Date(time));
			} catch (IllegalParamException e) {
				throw new JsonParseException(e.getMessage(),e);
			}
			
		} else {
			
			JsonPrimitive jsonPrimitive = jsonObj.get("value").getAsJsonPrimitive();
			try {
				if(jsonPrimitive.isBoolean()){
					return new EntryValue(jsonPrimitive.getAsBoolean());
				}
				if(jsonPrimitive.isNumber()){
					return new EntryValue(jsonPrimitive.getAsNumber());
				}
				return new EntryValue(jsonPrimitive.getAsString());
			} catch (IllegalParamException e) {
				throw new JsonParseException(e.getMessage(),e);
			}
			
		}
	}	
}
